package com.fpswork.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class FileUploadUtils {
	 //禁止上传的文件格式
	 private final static String  forbidExt = "jsp,exe,html,js,bat,jar,";
	 

	 	//上传文件到临时文件夹
		public static String upLoadFile(HttpServletRequest request,MultipartFile  myFile,String fileName){
			String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		    if(null==myFile || "".equals(myFile.getOriginalFilename())){
		    	return null;
		    }	
		    String sutuxs[]=(myFile.getOriginalFilename()).split("\\.");
	 		String sutux = sutuxs[sutuxs.length-1];
	 		fileName = sutux;
	 		//防止jsp，js，exe 植入
	 		if(forbidExt.indexOf(sutux.toLowerCase()) > -1 ){
	 			myFile = null;
	 			return null;
	 		}
		    //获得要上传的文件路径
			String newFileName="";
			String datatime=UUID.randomUUID().toString();
			 try  {
				 //查看文件夹或者目录是否已经存在
				 File fl=new File(filePath);
	             //不存在则创建一个文件夹或者目录
	             if ( ! (fl.exists())  &&   ! (fl.isDirectory()))  {
	            	 fl.mkdirs();
	             } 
	             newFileName = newFileName + "/"+(datatime)+"."+fileName;
	             //上传图片
	       		 File uploadfile = new java.io.File(filePath + newFileName);
	       		 if(!uploadfile.exists()){
	       			uploadfile.mkdirs();
	       		 }
	       		
	       		myFile.transferTo(uploadfile);
	         } catch (Exception e)  {
	            e.printStackTrace(); 
	        } 
			return  "uploadfile"+newFileName;
		}
    //上传文件
    public String upload(HttpServletRequest request) throws IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        String path = request.getSession().getServletContext().getRealPath("/upload");//设置磁盘缓冲路径
        factory.setRepository(new File(path));
        factory.setSizeThreshold(1024*1024);//设置创建缓冲大小
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);//设置上传文件限制大小,-1无上限
        String fileSrc = "";
        try {
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item : list){
                if(item.isFormField()){//判断是否是文件流
                }else {
                    String[] fileNames = getNewFileName(item);
                    //生成日期文件夹，新的文件名
                    String savePath =  createFile(path);
                    //保存
                    item.write(new File(path + "/" + savePath, fileNames[0]));
                    fileSrc = "/upload/"+savePath+"/"+fileNames[0];
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSrc;
    }

    private String[] getNewFileName(FileItem item){
        String value = item.getName();//会将完整路径名传过来
        int start = value.lastIndexOf("\\");
        String fileName = value.substring(start + 1);
        System.out.println(fileName);
        String[] extension = fileName.split("\\.");
        String newFileName = UUID.randomUUID()+"."+extension[1];
        return new String[]{ newFileName,fileName};
    }

    private String createFile(String path){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String savePath = format.format(date);
        //重新生成文件夹
        File file = new File(path+"/"+savePath);
        if(!file.exists()) {
            file.mkdirs();
        }
        return savePath;
    }
}
